<?php

namespace dkou\utils;
/**
 * 文件相关函数集
 * Class FileUtils
 * @package dkou\utils
 */
class FileUtils
{
    /**
     * 字节格式化，根据字节大小转换较大单位，如:1024B->1KB
     * @param $bytes
     * @param int $decimals
     * @return string
     */
    public static function byteFormat($bytes, $decimals = 2)
    {
        $exp = 0;
        $value = 0;
        $symbol = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        $bytes = (float)$bytes;
        if ($bytes > 0) {
            //换底公式 log(a)(x)=log(b)(x)/log(b)(a)
            $exp = floor(log($bytes) / log(1024));
            $value = $bytes / pow(1024, $exp);
        }
        if ($symbol[$exp] === 'B') {
            $decimals = 0;
        }
        return number_format($value, $decimals, '.', '') . '' . $symbol[$exp];
    }
}